package com.netflexitysolutions.amazonws.ec2.internal.operations;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.amazonaws.ec2.doc._2009_04_04.DescribeAddressesInfoType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeAddressesItemType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeAddressesResponseItemType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeAddressesResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeAddressesType;
import com.netflexitysolutions.amazonws.ec2.Address;
import com.netflexitysolutions.amazonws.ec2.EC2;

public class DescribeAddressesOperation extends ObjectSetOperationExecutor<DescribeAddressesType, List<Address>> {

	public DescribeAddressesOperation(EC2 ec2, Set<String> publicIps) {
		super(ec2, publicIps);
	}

	@Override
	protected List<Address> call(DescribeAddressesType request) {
		request.setPublicIpsSet(createAddressInfoElement());
		DescribeAddressesResponseType response = getEC2().getService().describeAddresses(request);
		List<Address> result = new ArrayList<Address>();
		if (response.getAddressesSet() != null) {
			List<DescribeAddressesResponseItemType> list = response.getAddressesSet().getItem();
			for (DescribeAddressesResponseItemType item : list) {
				result.add(new Address(item.getInstanceId(), item.getPublicIp()));
			}
		}
		return result;
	}
	
	private DescribeAddressesInfoType createAddressInfoElement() {
		DescribeAddressesInfoType info = new DescribeAddressesInfoType();
		List<DescribeAddressesItemType> list = info.getItem();
		for (String publicIp : objectIds) {
			DescribeAddressesItemType item = new DescribeAddressesItemType();
			item.setPublicIp(publicIp);
			list.add(item);
		}
		return info;
	}
}
